package com.ruoyi.utils;

import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Random;
import net.sf.json.JSONObject;

/* loaded from: ucpws-client.jar:com/sudytech/ucp/ws/util/TokenBuilder.class */
public class TokenBuilder {
    private String _appId;
    private String _privateKey;

    public TokenBuilder(String appId, String privateKey) {
        this._appId = appId;
        this._privateKey = privateKey;
    }

    public String buildToken() throws Exception {
        String timestamp = String.valueOf(System.currentTimeMillis());
        String nonce = String.valueOf(new Random().nextInt(10000));
        JSONObject jsonObj = new JSONObject();
        jsonObj.put("authType", "sign1");
        jsonObj.put("appId", this._appId);
        jsonObj.put("timestamp", timestamp);
        jsonObj.put("nonce", nonce);
        jsonObj.put("signature", buildSignature(this._privateKey, timestamp, this._appId, nonce));
        return jsonObj.toString();
    }

    private String buildSignature(String securyKey, String timestamp, String appId, String nonce) throws Exception {
        List<String> sParamList = new ArrayList<>();
        sParamList.add(securyKey);
        sParamList.add(timestamp);
        sParamList.add(nonce);
        sParamList.add(appId);
        Collections.sort(sParamList, new Comparator<String>() { // from class: com.sudytech.ucp.ws.util.TokenBuilder.1
            public int compare(String o1, String o2) {
                return o1.compareTo(o2);
            }
        });
        StringBuilder signature = new StringBuilder();
        for (String sParam : sParamList) {
            signature.append(sParam);
        }
        MessageDigest md = MessageDigest.getInstance("SHA-1");
        md.update(signature.toString().getBytes());
        return toHex(md.digest());
    }

    private String toHex(byte[] buffer) {
        StringBuilder sb = new StringBuilder(buffer.length * 2);
        for (int i = 0; i < buffer.length; i++) {
            sb.append(Character.forDigit((buffer[i] & 240) >> 4, 16));
            sb.append(Character.forDigit(buffer[i] & 15, 16));
        }
        return sb.toString();
    }
}